const express = require('express');
const router = express.Router();
const DateModel = require('../model/date');
const NodeModel = require('../model/node');



router.get('/range',async (req,res)=>{

    const { startDate, endDate } = req.query;


    const dateFilter = {};
    if (startDate) {
        dateFilter.date = { $gte: new Date(startDate) };
    }
    if (endDate) {
        dateFilter.date = { ...dateFilter.date, $lte: new Date(endDate) };
    }

    try {

        let rows = await DateModel.find(dateFilter).populate({path:'nodes',select: '-__v'}).select("-__v");

        res.json({
            code: 0,
            data: rows
        })

    } catch(e){
        res.send({
            code: 1,
            msg: e
        })
    }



})

router.post('/add',async (req,res)=>{


    let {date,sector,description,value} = req.body;

    try {


        let _date = await DateModel.findOne({ date: new Date(date) });
        if (!_date) {
            _date = new DateModel({
                date: new Date(date)
            });

            await _date.save();
        }


        const _node = new NodeModel({
            value: value,
            description: description,
            sector: sector,
            belong: _date._id
        })

        await _node.save();

        res.send({
            code: 0
        })


    } catch (e){
        res.send({
            code: 1,
            msg: e
        })
    }



})


router.post('/update',async (req,res)=>{
    let {date,sector,description,value,id} = req.body;


    try {
        const node = await NodeModel.findByIdAndUpdate(
        id,
        {date,sector,description,value},
        { new: true, runValidators: true }
        ).select('-__v');
        
        if (!node) {
            return res.send({ 
                code: 1,
                msg: '文章未找到'
             });
        }
        res.send({
            code: 0
        });
    } catch (err) {
        res.send({ 
            code: 1,
            msg: err.message 
        });
    }
})


router.post('/delete',async (req,res)=>{

    let id = req.body.id;

    try {
        await NodeModel.deleteOne({ _id: id });

        res.send({
            code: 0
        })

    } catch (e){
        console.error(e)
        res.send({
            code: 1,
            msg: e
        })
    }



})





module.exports = router;
